#include "GameDLL.h"
#include "SubWindow.h"

SubWindow::SubWindow() {
    _hInstance = HInstance();
}

SubWindow::~SubWindow() {
    UnregisterClass(_ClassName, _hInstance);
}

VOID SubWindow::RegisterNewClass() {
    WNDCLASSEX wc;

    wc.cbSize = sizeof(WNDCLASSEX);

    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = HandleMsgSetup;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = _hInstance;
    wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)CreateSolidBrush(RGB(50, 50, 50));
    wc.lpszMenuName = nullptr;
    wc.lpszClassName = _ClassName;

    wc.hIcon = _hIcon;
    wc.hIconSm = _hIcon;

    RegisterClassEx(&wc);
}


LRESULT SubWindow::HandleMsgSetup(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
    if (message == WM_NCCREATE) {
        const CREATESTRUCTW* const pCreate = reinterpret_cast<CREATESTRUCTW*>(lParam);
        SubWindow* const pWnd = static_cast<SubWindow*>(pCreate->lpCreateParams);
        SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(pWnd));
        SetWindowLongPtr(hWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(&SubWindow::HandleMsgThunk));
        return pWnd->HandleMsg(hWnd, message, wParam, lParam);
    }
    return DefWindowProc(hWnd, message, wParam, lParam);
}

LRESULT SubWindow::HandleMsgThunk(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
    SubWindow* const pWnd = reinterpret_cast<SubWindow*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
    return pWnd->HandleMsg(hWnd, message, wParam, lParam);
}

LRESULT SubWindow::ConmonMessapeHandler(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
    switch (message) {
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}